﻿using System;
using System.Xml;
using System.Text;
using Microsoft.Practices.RecipeFramework;
using Microsoft.Practices.RecipeFramework.Library;
using Conf = Microsoft.Practices.RecipeFramework.Configuration;
using Microsoft.Practices.RecipeFramework.Services;
using System.ComponentModel.Design;
using EnvDTE;
using ProjectBase.Guidance.Helpers;
using Microsoft.Practices.Common;
using System.Collections.Specialized;

namespace ProjectBase.Guidance.ValueProviders
{
    public class GuidValueProvider: ValueProvider, IAttributesConfigurable
    {
        /// <summary>
        /// Constants for handling string in xml recipes
        /// </summary>
        class Constants
        {
            Constants() { }
            public const string Expression = "Expression";
            public const string Format = "Format";
        }


        #region IAttributesConfigurable Members

        void IAttributesConfigurable.Configure(StringDictionary attributes)
        {
            if (!attributes.ContainsKey(Constants.Expression))
            {
                throw new ArgumentException("Expression argument in attributes is mandatory");
            }
        }

        #endregion

        public override bool OnBeginRecipe(object currentValue, out object newValue)
        {
            if (currentValue != null)
            {
                // Do not assign a new value, and return false to flag that
                // we don't want the current value to be changed.
                newValue = null;
                return false;
            }


            var cs = GetService<IConfigurationService>(true);

            Conf.Argument argument = cs.CurrentRecipe.ArgumentsByName[Argument.Name];

            var count = Utils.AttributeByName(argument.ValueProvider.AnyAttr, Constants.Expression);
            var format = Utils.AttributeByName(argument.ValueProvider.AnyAttr, Constants.Format);

            newValue = Guid.NewGuid().ToString(string.IsNullOrEmpty(format) ? "N" : format);

            int length;
            if (int.TryParse(count, out length))
            {
                var result = newValue.ToString();
                for (var i = 0; i < Math.Min(length, 5); i++)
                {
                    result += Guid.NewGuid().ToString(string.IsNullOrEmpty(format) ? "N" : format);
                }

                newValue = result.Substring(0, length);
            }

            return true;
        }
    }
}
